class_name MySprites
extends StaticBody2D

@export var max_health: int = 100
@export var health: int = 100
@export var attack: int = 20
@export var defence: int = 10
@export var is_player: bool = true
@export var current_position: int = 1
@export var anger: int = 0
@export var physical_position: int = 0
@export var is_current_turn_played: bool = false

func turn(players: Array, enemies: Array) -> void:
	is_current_turn_played = true
	if anger >= 4:
		await use_ultimate_ability(players, enemies)
		anger -= 4
	elif anger < 4:
		await use_basic_ability(players, enemies)
		anger += 2
		
func get_one_random_my_sprite(my_sprites: Array) -> StaticBody2D:
	var valid_sprites: Array = []
	for sprite in my_sprites:
		if is_instance_valid(sprite) and sprite.health > 0 and sprite.current_position != -1:
			valid_sprites.append(sprite)
	if valid_sprites.size() > 0:
		return valid_sprites[randi() % valid_sprites.size()]
	return null

func get_first_alive_my_sprite(my_sprites: Array) -> StaticBody2D:
	for sprite in my_sprites:
		if is_instance_valid(sprite) and sprite.health > 0 and sprite.current_position != -1:
			return sprite
	return null
	
func one_sprites_hited(target_enemy: StaticBody2D, damage: int):
	target_enemy.health -= damage
	Events.signal_health_reduce.emit(damage)
	if target_enemy.health <= 0:
		target_enemy.health = 0
		target_enemy.my_sprite_killed()
		await target_enemy.animation_player.animation_finished
		
func heal_self(self_player: StaticBody2D, heal_value: int) -> void:
	self_player.health += heal_value
	if self_player.health >= self_player.max_health:
		self_player.health = self_player.max_health
	
func switch_turn(st_is_player: bool) -> void:
	if st_is_player:
		Events.signal_enemy_turn.emit()
	else:
		Events.signal_player_turn.emit()

func play_basic_animation(animation_player: AnimatedSprite2D) -> void:
	animation_player.play("Attack")
	await animation_player.animation_finished

func play_ultimate_animation(animation_player: AnimatedSprite2D) -> void:
	animation_player.play("Attack")
	await animation_player.animation_finished

func play_idle_animation(animation_player: AnimatedSprite2D) -> void:
	animation_player.play("Idle")

func use_ultimate_ability(_players: Array, _enemies: Array) -> void:
	pass

func use_basic_ability(_players: Array, _enemies: Array) -> void:
	pass
	
func my_sprite_killed() -> void:
	pass
